package com.lishe.lishe.lishe.module.mall.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.LoginFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.adapter.ImageViewPagerAdapter;
import com.lishe.lishe.lishe.base.BaseFragment;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.commonclass.SearchActivity;
import com.lishe.lishe.lishe.module.commonclass.WebActivity;
import com.lishe.lishe.lishe.module.excitation.bean.BannerObject;
import com.lishe.lishe.lishe.module.mall.adapter.GlideImageLoader;
import com.lishe.lishe.lishe.module.mall.adapter.MallClassifyAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallMaybeLikeAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallRecyClerViewAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallSelectActivityAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallTitleActivityAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallValuseAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.MallItemObject;
import com.lishe.lishe.lishe.module.mall.bean.MallObject;
import com.lishe.lishe.lishe.module.mall.bean.WrapContentLinearLayoutManager;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.shopingcart.activity.ShoppingCartActivity;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/11/6.
 * 商城首页
 */

public class MallFragemtn extends BaseFragment implements View.OnClickListener {

    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private MallRecyClerViewAdapter adapter;
    private TextView search;
    private RelativeLayout emptylayout;
    private TextView emptyText;
    private ImageView goods_cart;
    private TextView goods_count;

    private MallObject mallObjectLun = new MallObject();//轮播图数据
    private MallObject mallObjectLove = new MallObject();//猜你喜欢数据
    private List<MallObject> mallObjects = new ArrayList<>();//首页模块

    private int pageIndex = 0;
    private int oldIndex = 0;
    private LinkedList<ImageView> imageViews = new LinkedList<>();//轮播的图片
    private LinkedList<View> points = new LinkedList<>();//轮播的图片的小圆点
    private ImageLoaderUtils imageLoaderUtils;
    private int page = 1;
    private int pageSize = 10;
    private int totalPage = 0;

    private String keyword = null;
    //-----------不同类型的adapter-----------------
    private MallTitleActivityAdapter mallTitleActivityAdapter;//首页大推荐
    private MallClassifyAdapter mallClassifyAdapter;//导航分类
    private MallValuseAdapter mallValuseAdapter;//超值专区
    private MallSelectActivityAdapter mallSelectActivityAdapter;//精选活动
    private MallMaybeLikeAdapter mallMaybeLikeAdapter;//猜你喜欢


    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, MallFragemtn.class);
        activity.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new MallRecyClerViewAdapter(getActivity(), mallObjects);
        imageLoaderUtils = new ImageLoaderUtils();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_mall0, null);
        initView(view);
        view.setOnTouchListener(this);
        return view;
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void initView(View v) {
        goods_cart = v.findViewById(R.id.goods_cart);
        goods_count = v.findViewById(R.id.goods_count);
        emptylayout = v.findViewById(R.id.empty_layout);
        emptyText = v.findViewById(R.id.empty_text);
        search = v.findViewById(R.id.search);
        recyclerView = v.findViewById(R.id.recyclerView);
        refreshLayout = v.findViewById(R.id.refreshlayout);
        WrapContentLinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(getActivity());
        layoutManager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

//        recyclerView.setOnRefreshListener(new RecyclerViewRefreshListener() {
//            @Override
//            public void onHeaderRefresh(View headerView) {
//                recyclerView.setFooterRefreshEnabled(true);
//                page = 1;
//                totalPage = 0;
//                getMallMain();
//            }
//
//            @Override
//            public void onFooterRefresh(View footerViwe) {
//                if (page <= totalPage) {
//                    recyclerView.setFooterRefreshEnabled(true);
//                    getMaybeLove();
//                } else {
//                    recyclerView.setFooterRefreshEnabled(false);
//                }
//            }
//        });
//        recyclerView.setRefreshing();
        if (mallObjects.size() == 0) {
            emptylayout.setVisibility(View.VISIBLE);
            emptyText.setText("加载中!");
        } else {
            emptylayout.setVisibility(View.GONE);
        }
        refreshLayout.setEnableLoadmore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.setLoadmoreFinished(false);
                page = 1;
                totalPage = 0;
                if (mallObjectLove.getItemObject() != null) {
                    mallObjectLove.getItemObject().clear();
                }
                getMallMain();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (page <= totalPage) {
                    refreshlayout.setLoadmoreFinished(false);
                    getMaybeLove();
                } else {
                    refreshlayout.finishLoadmore();
                    refreshlayout.setLoadmoreFinished(true);
                }
            }
        });
        refreshLayout.autoRefresh();
        setListener();
    }

    private void setListener() {
        search.setOnClickListener(this);
        goods_cart.setOnClickListener(this);
        recyclerView.setOnTouchListener(//避免更新数据是刷新闪退
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (refreshLayout.isRefreshing()) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
        );
    }

    /**
     * 获取首页数据
     */
    private void getMallMain() {
        HttpMall.getMallMain(responseHandler);
    }

    /**
     * 获取首页-猜你喜欢
     */
    private void getMaybeLove() {
        try {
            HttpMall.getMaybeLove(page + "", pageSize + "", "getMaybeLove", maybeLoveRespon);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    AsyncHttpResponseHandler maybeLoveRespon = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            refreshLayout.finishLoadmore();
            Log.e("猜你喜欢", data);
            try {
                JSONObject json = new JSONObject(data);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject dataObject = json.optJSONObject("data");
                    MallItemObject mallItemObject;
                    if (page == 1) {
                        mallObjectLove = JSON.parseObject(dataObject.toString(), MallObject.class);
                        mallItemObject = new MallItemObject();
                        mallObjects.add(mallObjectLove);
                    } else {
                        mallItemObject = mallObjectLove.getItemObject().get(0);
                    }
                    JSONArray items = dataObject.optJSONArray("items");

                    totalPage = dataObject.optInt("totalPage");
                    page = page + 1;
                    Log.e("page"+page,"totalPage"+totalPage);
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject item = items.optJSONObject(i);
                        MallGoods mallGoods = new MallGoods();
                        mallGoods = JSON.parseObject(item.toString(), MallGoods.class);
                        mallItemObject.getMallGoodsItem().add(mallGoods);
                    }
                    mallObjectLove.getItemObject().add(mallItemObject);
                    mallMaybeLikeAdapter = null;
                    mallMaybeLikeAdapter = new MallMaybeLikeAdapter(context, mallObjectLove.getItemObject().get(0).getMallGoodsItem());
                    mallObjectLove.setAdapter(mallMaybeLikeAdapter);
                    Collections.sort(mallObjects, new Comparator<MallObject>() {
                        @Override
                        public int compare(MallObject mallObject, MallObject t1) {//取倒叙
                            return t1.getSort().compareTo(mallObject.getSort());
                        }
                    });
                }
                notifyAdapter();
            } catch (Exception e) {
                e.printStackTrace();
                notifyAdapter();
//                toast("数据异常" + data);
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("网络或服务器异常！");
            refreshLayout.finishLoadmore();
            notifyAdapter();
        }
    };
    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            refreshLayout.finishRefresh();
            String result = new String(responseBody);
            getMaybeLove();
            Log.e("商城首页", result);
            try {
                JSONObject jsonObject = new JSONObject(result);
                if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                    mallObjects.clear();
                    JSONArray dataArray = jsonObject.optJSONArray("data");
                    for (int j = 0; j < dataArray.length(); j++) {
                        MallObject mallObject = new MallObject();
                        JSONObject data = dataArray.optJSONObject(j);
                        mallObject = JSON.parseObject(data.toString(), MallObject.class);
                        mallObject.getItemObject().clear();
                        JSONArray codeData = data.optJSONArray(mallObject.getCode());
                        if (codeData != null) {
                            for (int i = 0; i < codeData.length(); i++) {
                                JSONObject json = codeData.optJSONObject(i);
                                MallItemObject mallItemObject = new MallItemObject();
                                mallItemObject = JSON.parseObject(json.toString(), MallItemObject.class);
                                if (mallObject.getStyle().equals("activityStyle")) {//精选活动
                                    JSONArray itemArray = json.optJSONArray("items");
                                    mallItemObject.getMallGoodsItem().clear();
                                    for (int k = 0; k < itemArray.length(); k++) {
                                        JSONObject item = itemArray.optJSONObject(k);
                                        MallGoods mallGoods = new MallGoods();
                                        mallGoods = JSON.parseObject(item.toString(), MallGoods.class);
                                        mallItemObject.getMallGoodsItem().add(mallGoods);
                                    }
                                    JSONObject moreObject = json.optJSONObject("more");
                                    if (moreObject != null) {
                                        MallGoods more = new MallGoods();
                                        more.setImage_default_id(moreObject.optString("more_goods_img"));
                                        more.setItem_id(moreObject.optString("activity_config_id"));
                                        more.setTitle("more");
                                        mallItemObject.getMallGoodsItem().add(more);
                                    }
                                }
                                mallObject.getItemObject().add(mallItemObject);
                            }
                        }
                        if (mallObject.getStyle().equals("indexBannerStyle")) {
                            mallObjectLun = mallObject;
                        } else {
                            if (mallObject.getStyle().equals("recommendStyle")) {//活动主题
                                mallTitleActivityAdapter = null;
                                mallTitleActivityAdapter = new MallTitleActivityAdapter(context, mallObject.getItemObject());
                                mallObject.setAdapter(mallTitleActivityAdapter);
                            }
                            if (mallObject.getStyle().equals("cateStyle")) {//导航栏
                                mallClassifyAdapter = null;
                                mallClassifyAdapter = new MallClassifyAdapter(context, mallObject.getItemObject());
                                mallObject.setAdapter(mallClassifyAdapter);

                            }
                            if (mallObject.getStyle().equals("valueStyle")) {//超值专区
                                mallValuseAdapter = null;
                                mallValuseAdapter = new MallValuseAdapter(context, mallObject.getItemObject());
                                mallObject.setAdapter(mallValuseAdapter);
                            }
                            if (mallObject.getStyle().equals("activityStyle")) {//精选活动
                                mallSelectActivityAdapter = null;
                                mallSelectActivityAdapter = new MallSelectActivityAdapter(context, mallObject.getItemObject());
                                mallObject.setAdapter(mallSelectActivityAdapter);
                            }
                            mallObjects.add(mallObject);
                        }
                    }
                    if (mallObjects.size() == 0) {
                        emptylayout.setVisibility(View.VISIBLE);
                        emptyText.setText("还没有商品！");
                    } else {
                        emptylayout.setVisibility(View.GONE);
                    }
                    View view = initHeaderView();
                    if (view != null) {
                        adapter.addHeaderView(view);
                    }
                } else {
                    toast(jsonObject.optString("msg"));
                }

                notifyAdapter();
            } catch (JSONException e) {
                notifyAdapter();
                if (mallObjects.size() == 0) {
                    emptylayout.setVisibility(View.VISIBLE);
                    emptyText.setText("加载中!");
                } else {
                    emptylayout.setVisibility(View.GONE);
                }
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            refreshLayout.finishRefresh();
            notifyAdapter();
            if (mallObjects.size() == 0) {
                emptylayout.setVisibility(View.VISIBLE);
                emptyText.setText("服务器或网络异常！！");
            } else {
                emptylayout.setVisibility(View.GONE);
            }
        }
    };

    private void notifyAdapter() {
//        if (mallTitleActivityAdapter != null) {
//            mallTitleActivityAdapter.notifyDataSetChanged();
//        }
//        if (mallClassifyAdapter != null) {
//            mallClassifyAdapter.notifyDataSetChanged();
//        }
//        if (mallValuseAdapter != null) {
//            mallValuseAdapter.notifyDataSetChanged();
//        }
//        if (mallSelectActivityAdapter != null) {
//            mallSelectActivityAdapter.notifyDataSetChanged();
//        }
//        if (mallMaybeLikeAdapter != null) {
//            mallMaybeLikeAdapter.notifyDataSetChanged();
//        }
//        for(int i=0;i<mallObjects.size();i++){
//            if( mallObjects.get(i).getAdapter()!=null){
//                mallObjects.get(i).getAdapter().notifyDataSetChanged();
//            }
//        }
//        adapter.notifyDataSetChanged();
        //1秒后刷新
        Log.e("Mallfragment刷新", "0");
        i = 0;
        notifyHandler.removeCallbacks(runnable);
        notifyHandler.postDelayed(runnable, 0);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        notifyHandler.removeCallbacks(runnable);
    }

    private View initHeaderView() {
        if (getActivity() == null) {
            return null;
        }
        View v = getActivity().getLayoutInflater().inflate(R.layout.item_banner, null, false);
        Banner banner = v.findViewById(R.id.banner);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(mallObjectLun.getItemObject());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                final MallItemObject mallItemObject = mallObjectLun.getItemObject().get(position);
                if (!TextUtils.isEmpty(mallItemObject.getLink_url())) {
                    WebActivity.jump(getActivity(), mallItemObject.getLink_url());
                }
            }
        });
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        return v;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search:
                SearchActivity.jump(getActivity(), Globals.REQUSE_CODE_SearchActivity, true);
                break;
            case R.id.goods_cart:
                ShoppingCartActivity.jump(getActivity(), true);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!LSWebHelper.getInstance().isUserLogined()) {
            goods_cart.setVisibility(View.GONE);
        } else {
            goods_cart.setVisibility(View.VISIBLE);
            getGoodsCount();
        }
    }

    private void getGoodsCount() {
        HttpMall.getGoodsCountFromShoppingCart(Globals.getToken(), getGoodsCountRespose);
    }

    /**
     * 商品数量
     */
    AsyncHttpResponseHandler getGoodsCountRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("购物车商品数量", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject data = json.optJSONObject("data");
                    int num = data.optInt("num");
                    if (num > 0) {
                        goods_count.setText(num + "");
                        goods_count.setVisibility(View.VISIBLE);
                    } else {
                        goods_count.setVisibility(View.GONE);
                    }
                } else {
                    goods_count.setVisibility(View.GONE);
                    LoadingUtils.closeDialog();
                    JSONObject msgObject = json.optJSONObject("msg");
                    String msgString = StringUtils.unicodeToString("msg", msgObject.toString());
                    Log.e("商品", "" + msgString);
                    if (msgString != null && msgString.contains("请登录")) {
                        toast("还未登录，无法获取购物车信息！");
                    } else {
                        toast(msgString);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(getString(R.string.network_or_server_exception));
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case Globals.REQUSE_CODE_SearchActivity:
                    keyword = data.getStringExtra("keyword");
                    if (TextUtils.isEmpty(keyword)) {
                        search.setGravity(Gravity.CENTER);
                        search.setText("");
                    } else {
                        search.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
                        search.setText("");
                    }
                    break;
            }
        }
    }

    int i = 0;
    Handler notifyHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.e("刷新", "0--" + i);
            i = i + 1;
//            notifyHandler.postDelayed(this, 1000);
            if(getActivity()==null){
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < mallObjects.size(); i++) {
                        if (mallObjects.get(i).getAdapter() != null) {
                            mallObjects.get(i).getAdapter().notifyDataSetChanged();
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            if (i == 5) {
                notifyHandler.removeCallbacks(this);
            }
        }
    };
}
